if (window.io == null) {
    window.io = require("socket-io");
}

var Global = cc.Class({
    extends: cc.Component,
    statics: {
        ip: "",
        sio: null,
        isPinging: false,
        isReconnectOk: false, //表示重连监控是否load完毕
        fnDisconnect: null,
        handlers: {},
        addHandler: function(event, fn) {
            if (this.handlers[event]) {
                console.log("event:" + event + "' handler has been registered.");
                return;
            }

            var handler = function(data) {
                //console.log(event + "(" + typeof(data) + "):" + (data? data.toString():"null"));
                if (event != "disconnect" && typeof(data) == "string") {
                    data = JSON.parse(data);
                }
                fn(data);
            };

            this.handlers[event] = handler;
            if (this.sio) {
                console.log("register:function " + event);
                this.sio.on(event, handler);
            }
        },
        connect: function(fnConnect, fnError) {
            var self = this;

            var opts = {
                'reconnection': false,
                'force new connection': true,
                'transports': ['websocket', 'polling']
            }
            this.sio = window.io.connect(this.ip, opts);

            this.sio.on('reconnect', function() {
                console.log('websocket  reconnection');
            });
            this.sio.on('connect', function(data) {
                //防止连接的回调在心跳 超时之后
                if (self.sio) {
                    self.sio.connected = true;
                    fnConnect(data);
                    self.startHearbeat();
                }
                console.log('websocket  connect');
            });

            this.sio.on('disconnect', function(data) {
                console.log("websocket disconnect");
                if (self.sio) {
                    self.sio.connected = false;
                }
                self.reconnect();
            });
            //连接失败 直接重连
            this.sio.on('connect_error', function() {
                console.log('websocket  connect_error');
                fnError();
                self.reconnect();
            });

            //连接超时直接重连
            this.sio.on('connect_timeout', function() {
                console.log('websocket  connect_timeout');
                fnError();
                self.reconnect();
            });

            for (var key in this.handlers) {
                var value = this.handlers[key];
                if (typeof(value) == "function") {
                    if (key == 'disconnect') {
                        this.fnDisconnect = value;
                        console.log("disconnect事件添加");
                    } else {
                        console.log("register:function " + key);
                        this.sio.on(key, value);
                    }
                }
            }

            // this.startHearbeat();
        },
        startHearbeat: function() {

            
            var self = this;
            self.pingCount = 0; //一定要发一次服务器的ping请求
            console.log("websocket startHerbeat...");
            //基数第一次心跳检测
            this.sio.on('game_pong', function() {
                self.lastRecieveTime = Date.now();
                // console.log('websocket  game_pong...');
            });
            this.lastRecieveTime = Date.now();
            if (!self.isPinging) {
                self.isPinging = true;
                console.log("websocket startHerbeat  开启定时任务...");
                setInterval(function() {
                    // console.log('task :' + Date.now());
                    if (self.sio && self.sio.connected) {
                        if ((Date.now() - self.lastRecieveTime > 9000) && self.pingCount > 0) {
                            // console.log("websocket 心跳超时...");
                            self.close()
                        } else {
                            self.ping();
                            if(self.pingCount==0){
                                self.pingCount = 1;
                                self.lastRecieveTime = Date.now();
                            }
                            
                        }
                    }
                }, 3000);
            }
        },
        send: function(event, data,callback) {
            if (this.sio && this.sio.connected) {
                if (data != null && (typeof(data) == "object")) {
                    data = JSON.stringify(data);
                    console.log('发送参数' + data);
                }
                this.sio.emit(event, data);
                if (callback) {
                    callback()
                }
            } else {
                console.log('websocet send  ',data);
                this.reconnect()
            }
        },

        ping: function() {
            this.send('game_ping');
            // console.log('websocket  game_ping...');
        },
        //重连：如果重连函数存在就发起重连
        reconnect: function() {
            this.sio = null;
            if (this.fnDisconnect) {
                console.log("websocket 执行注册的重连函数...");
                this.fnDisconnect();
                this.fnDisconnect = null;
            }
        },

        close: function() {
            console.log('websocket  close...');
            //如果websocket依然存在 则断开,如果不存在则重连
            if (this.sio && this.sio.connected) {
                //触发disconnect事件去处理
                this.sio.connected = false;
                //ios 网络断开不触发disconnect事件
                this.sio.disconnect();
                this.reconnect()
            }
        },
        // close: function() {
        //     console.log('websocket  close...');
        //     if (this.sio && this.sio.connected) {
        //         this.sio.connected = false;
        //         this.sio.disconnect();
        //         this.sio = null;
        //         console.log("websocket 断开连接...");
        //     }
        //     if (this.fnDisconnect) {
        //         console.log("websocket 执行注册的重连函数...");
        //         this.fnDisconnect();
        //         this.fnDisconnect = null;
        //     }
        // },

        test: function(fnResult) {
            var xhr = null;
            var fn = function(ret) {
                fnResult(ret.isonline);
                xhr = null;
            }

            var arr = this.ip.split(':');
            var data = {
                account: cc.vv.userMgr.account,
                sign: cc.vv.userMgr.sign,
                ip: arr[0],
                port: arr[1],
            }
            xhr = cc.vv.http.sendRequest("/is_server_online", data, fn);
            setTimeout(function() {
                if (xhr) {
                    xhr.abort();
                    fnResult(false);
                }
            }, 1500);
            /*
            var opts = {
                'reconnection':false,
                'force new connection': true,
                'transports':['websocket', 'polling']
            }
            var self = this;
            this.testsio = window.io.connect(this.ip,opts);
            this.testsio.on('connect',function(){
                console.log('connect');
                self.testsio.close();
                self.testsio = null;
                fnResult(true);
            });
            this.testsio.on('connect_error',function(){
                console.log('connect_failed');
                self.testsio = null;
                fnResult(false);
            });
            */
        }
    },
});